// =================================================================
// File: cp.cpp
// Desc: Contains function for copying a file
// =================================================================

// =================================================================
// INCLUDES
// =================================================================

#include <string>
#include "FSManager.h"
#include "commands.h"
#include "Directory.h"
#include "File.h"
#include "Inode.h"

using namespace std;

// =================================================================
// FUNCTIONS
// =================================================================

// =================================================================
// Name: cp
// Desc: Copies a file located at src_path to dest_path
// Args: string src_path - file to copy
//       string dest_path - location of new file
//       FSManager* fsm - pointer to FSManager object in use
// Rets: 0 on success, -1 on failure
// =================================================================
int cp(string src_path, string dest_path, FSManager *fsm){
 
  size_t found;
  Directory *dest_dir;
  string filename;
  Inode *node;

  //Check if the file already exists
  found = dest_path.find_last_of("/");
  
  if(found == string::npos){
    dest_dir = fsm->GetCurrentDirectory();
  }
  else{
    dest_dir = fsm->ReadDirectory(dest_path.substr(0,found));
  }
    filename = dest_path.substr(found+1);
    if(dest_dir->GetEntry(filename) != -1){
      return -1;
  }

  // Read data from the existing file
  int fd = open(src_path,"r",fsm);

  File *file_src = fsm->GetOpenFile(fd);
  node = fsm->ReadInode(file_src->GetInodeIndex());
  string data = read(fd,node->GetSize(),fsm);
  data += '\0';
  close(fd,fsm);

  // Copy data into new file
  fd = open(dest_path,"w",fsm);
  write(fd,data,fsm);
  close(fd,fsm);

  cout << src_path << " copied to " << dest_path << endl;


  return 0;
}

